package com.ias.agdis_r.activity.task;

import android.app.ActionBar;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import com.ias.agdis_r.R;
import com.ias.agdis_r.activity.BaseActivity;
import com.ias.agdis_r.activity.MainActivity;
import com.ias.agdis_r.adapter.TaskMonitorAdapter;
import com.ias.agdis_r.bean.auth.AuthEnum;
import com.ias.agdis_r.bean.task.Task;
import com.ias.agdis_r.bean.task.TaskProcess;
import com.ias.agdis_r.bean.task.TaskServiceLabel;
import com.ias.agdis_r.manager.DataManager;
import com.ias.agdis_r.manager.EffectManager;
import com.ias.agdis_r.manager.JavaBeanManager;
import com.ias.agdis_r.module.MessageModel;
import com.ias.agdis_r.module.ParameterModel;
import com.ias.agdis_r.terminalmanager.restful.base.endpoint.response.BaseResponse;
import com.ias.agdis_r.terminalmanager.restful.task.endpoint.request.SubmittaskprocssRequest;
import com.ias.agdis_r.terminalmanager.restful.task.endpoint.response.SubmittaskmarkResponse;
import com.ias.agdis_r.terminalmanager.restful.task.endpoint.response.SubmittaskprocssResponse;
import com.ias.agdis_r.terminalmanager.restful.task.vo.SubmitTaskProcessRequestVO;
import com.ias.agdis_r.util.S;
import com.ias.agdis_r.util.flight.AirlineCompanyUtil;
import com.ias.agdis_r.util.network.HttpUtil;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;

/**
 * 任务监控界面
 *
 * @author guoxr
 */
public class TaskMonitorActivity extends BaseActivity implements OnClickListener {
    private SubmittaskprocssRequest submittaskprocssRequest;
    private Button btn_change;
    private TextView txt_flight_no, txt_flight_reg;
    private TextView title;
    private ImageView iv_flight_company, iv_flight_adid;
    private ListView lv_monitor;
    private ArrayList<HashMap<String, Object>> list_service;
    private ArrayList<HashMap<String, Object>> list_process;
    private ArrayList<HashMap<String, Object>> mylist;
    private TaskMonitorAdapter mSchedule;
    private boolean bListService = false;
    private String sTNB = "";
    private Task task = null;
    private ActionBar actionBar;
    private AlertDialog dialog;
    private boolean isNFTask = false;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_taskmonitor);
        actionBar = getActionBar();
        taskmonitoractionbar();
        Intent intent = getIntent();
        sTNB = intent.getExtras().getString(MessageModel.TNB);
        btn_change = (Button) findViewById(R.id.bottom_button3);
        iv_flight_company = (ImageView) findViewById(R.id.iv_flight_company);
        iv_flight_adid = (ImageView) findViewById(R.id.iv_flight_adid);
        txt_flight_no = (TextView) findViewById(R.id.txt_flight_no);
        txt_flight_reg = (TextView) findViewById(R.id.txt_flight_reg);
        lv_monitor = (ListView) findViewById(R.id.listview_monitor);
        btn_change.setText(R.string.service_label);
        task = DataManager.getInstance().getWorkTask(sTNB);
        if (task != null){
            if ((S.valueOf(task.getTaskInfo().getAOD())).equals("D")) {
                iv_flight_adid.setBackgroundResource(R.drawable.adidd);
            } else {
                iv_flight_adid.setBackgroundResource(R.drawable.adida_red);
            }
            String fln = task.getTaskInfo().getFLN();
            iv_flight_company.setBackgroundResource(AirlineCompanyUtil.getArilineCompanyIconResourceId(fln));
            txt_flight_no.setText(fln);
            String sFlightNum = S.valueOf(task.getTaskInfo().getREG());
            txt_flight_reg.setText(sFlightNum);
        } else {
            task = DataManager.getInstance().getWorkNFTask(sTNB);
            txt_flight_no.setText(task.getTaskInfo().getTNM());
            txt_flight_reg.setText(task.getTaskInfo().getTTP());
            isNFTask = true;
        }
        list_service = new ArrayList<HashMap<String, Object>>();
        list_process = new ArrayList<HashMap<String, Object>>();
        mylist = new ArrayList<HashMap<String, Object>>();
        btn_change.setOnClickListener(this);
    }

    /**
     * 重新加载服务标注
     */
    @Override
    protected void onResume() {
        // TODO Auto-generated method stub
        if (task.getPID().equals(MessageModel.TCXX)
                || task.getPID().equals(MessageModel.TEND)
                || task.getPID().equals(MessageModel.TRJT)) {
            finish();
        }
        super.onResume();
        // 加载服务标注数据
        loadStandardInfo();
        // 加载监控项数据
        loadMonitorInfo();
        if (mSchedule != null) {
            mSchedule.notifyDataSetChanged();
        } else {
            // 初始化View
            initView();
        }
    }

    private void taskmonitoractionbar() {
        // TODO Auto-generated method stub
        actionBar.setCustomView(LayoutInflater.from(TaskMonitorActivity.this)
                .inflate(R.layout.actionbar_back_and_home, null));
        actionBar.setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM);
        actionBar.setDisplayShowCustomEnabled(true);
        title = (TextView) findViewById(R.id.txt_title);
        title.setText(R.string.TaskMonitorActivity);
        ImageView back = (ImageView) findViewById(R.id.action_back);
        back.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View arg0) {
                finish();
            }
        });
        ImageView home = (ImageView) findViewById(R.id.action_home);
        home.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(TaskMonitorActivity.this, MainActivity.class);
                intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                startActivity(intent);
            }
        });
    }

    private void showButton() {
        if (list_service.size() == 0) {
            btn_change.setVisibility(View.INVISIBLE);
        }
        if (list_process.size() == 0) {
            btn_change.setVisibility(View.INVISIBLE);
        }
    }

    /**
     * 加载服务标注数据
     */
    private void loadStandardInfo() {
        if (list_service == null) {
            return;
        }
        list_service.clear();
        if (task != null) {
            HashMap<String, TaskServiceLabel> serviceLabel = task
                    .getServiceLabelMap();
            Iterator<String> iterator = serviceLabel.keySet().iterator();
            String key = "";
            while (iterator.hasNext()) {
                key = (String) iterator.next();
                TaskServiceLabel taskServiceLabel = task.getServiceLabel(key);
                if (isNFTask && !taskServiceLabel.getIsMark()){
                    continue;
                }
                HashMap<String, Object> serviceMap = new HashMap<String, Object>();
                serviceMap.put("MONITOR_TYPE", taskServiceLabel.getMKID());
                serviceMap.put("MONITOR_ITEM", taskServiceLabel.getMKNM());
                serviceMap.put("MONITOR_STATUS", "");
                serviceMap.put("MONITOR_CONTENT", S.valueOf(taskServiceLabel.getCTNT()));
                list_service.add(serviceMap);
            }
        }
    }

    /**
     * 加载监控项数据
     */
    private void loadMonitorInfo() {
        if (list_process == null) {
            return;
        }
        list_process.clear();
        if (task != null) {
            HashMap<String, TaskProcess> processLabel = task.getProcessMap();
            Iterator<String> iterator = processLabel.keySet().iterator();
            String key = "";
            while (iterator.hasNext()) {
                key = (String) iterator.next();
                TaskProcess taskProcess = task.getProcess(key);
                // 如果是监控项
                if ("N".equals(taskProcess.getIFSW())) {
                    HashMap<String, Object> processMap = new HashMap<String, Object>();
                    processMap.put("MONITOR_TYPE", taskProcess.getPCID());
                    processMap.put("MONITOR_ITEM", taskProcess.getPCNM());
                    processMap.put("MONITOR_STATUS", "");
                    processMap.put("MONITOR_TIME",
                            S.valueOf(taskProcess.getATIM()));
                    processMap.put("MONITOR_CONTENT", S.FormatTimeHCCMonitorNoExe(S.valueOf(taskProcess.getATIM())));
                    list_process.add(processMap);
                }
            }
        }
    }

    /**
     * 显示监控项页面
     */
    private void showMonitorView() {
        if (title!=null){
            title.setText(R.string.TaskMonitorActivity);
        }
        btn_change.setText(R.string.service_label);
        mylist = list_process;
        onShowInfo("CB");
    }

    /**
     * 显示服务标注页面
     */
    private void showStandardView() {
        if (title!=null){
            title.setText(R.string.TaskMonitor_service_label);
        }
        btn_change.setText(R.string.monitor);
        mylist = list_service;
        onShowInfo("BZ");
    }

    private void initView() {
        if (list_process.size() != 0) {
            mylist = list_process;
            // 显示监控项项页面
            showMonitorView();
        } else if (list_service.size() != 0) {
            bListService = true;
            mylist = list_service;
            // 显示服务标注项页面
            showStandardView();
        } else {
            mylist = list_process;
            // 显示监控项项页面
            showMonitorView();
        }
        showButton();
    }

    protected void function_well() {
        if (btn_change.getVisibility() == View.VISIBLE) {
            if (list_service.size() < 1) {
                EffectManager.getInstance().ttsPlay(EffectManager.TTS_TYPE_TASK, getString(R.string.cantChange), false);
                return;
            }
            bListService = !bListService;
            if (null != dialog) {
                dialog.dismiss();
            }
            if (bListService) {
                showStandardView();
            } else {
                showMonitorView();
            }
        }
    }

    private void onShowInfo(String type) {
        if (mylist != null) {
            mSchedule = new TaskMonitorAdapter(TaskMonitorActivity.this, mylist, sTNB, type);
            lv_monitor.setAdapter(mSchedule);
            lv_monitor.setOnItemClickListener(new OnItemClickListener() {
                @Override
                public void onItemClick(AdapterView<?> parent, View view,
                                        int position, long id) {
                    mSchedule.setSelectItem(position);
                    mSchedule.notifyDataSetChanged();
                    parent.setSelection(position);
                }
            });
            lv_monitor.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
                @Override
                public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
                    if (!bListService) {
                        mSchedule.setSelectItem(position);
                        mSchedule.notifyDataSetChanged();
                        if (dialog != null && dialog.isShowing()) {
                            dialog.dismiss();
                        }
                        openConfirm(position);
                    }
                    return false;
                }
            });
        }
    }

    public void openConfirm(final int position) {
        AlertDialog.Builder builder = new AlertDialog.Builder(TaskMonitorActivity.this);
        builder.setTitle(getString(R.string.prompt));
        builder.setMessage(getString(R.string.isReport));
        builder.setIcon(android.R.drawable.ic_dialog_info);
        builder.setPositiveButton(getString(R.string.confirm),
                new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {
                        sendMonitorReport(position);
                        dialog.dismiss();
                    }
                });
        if(JavaBeanManager.getInstance().adjust_pri(AuthEnum.AI_T_TASKMONITORNOEX.toString())) {
            builder.setNeutralButton(getString(R.string.monitor_no_exe),
                    new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            sendNoExeReport(position);
                            dialog.dismiss();
                        }
                    });
        }
        builder.setNegativeButton(getString(R.string.cancel), null);
        dialog = builder.create();
        dialog.show();
    }

    /**
     * 发送上报监控项消息
     *
     * @param _nSelect
     */
    private void sendMonitorReport(int _nSelect) {
        HashMap<String, Object> hashmapM = mylist.get(_nSelect);
        String cotent = S.valueOf(hashmapM.get("MONITOR_CONTENT"));
        if (S.isNotEmpty(cotent)) {
            EffectManager.getInstance().ttsPlay(EffectManager.TTS_TYPE_UPTO,
                    getString(R.string.monitorReported), false);
        } else {
            String sMki = S.valueOf(hashmapM.get("MONITOR_TYPE"));
            String sTnb = S.valueOf(sTNB);
            initTRPT(sTnb, sMki, null, "");
            HttpUtil.getInstance().sendRequest(submittaskprocssRequest, MessageModel.TRPT,
                    true);
        }
    }

    /**
     * 发送不执行监控项消息
     * @param _nSelect
     */
    private void sendNoExeReport(int _nSelect) {
        HashMap<String, Object> hashmapM = mylist.get(_nSelect);
        String cotent = S.valueOf(hashmapM.get("MONITOR_CONTENT"));
        if (S.isNotEmpty(cotent)) {
            EffectManager.getInstance().ttsPlay(EffectManager.TTS_TYPE_UPTO,
                    getString(R.string.monitorReported), false);
        } else {
            String sMki = S.valueOf(hashmapM.get("MONITOR_TYPE"));
            String sTnb = S.valueOf(sTNB);
            initTRPT(sTnb, sMki, null, "X");
            HttpUtil.getInstance().sendRequest(submittaskprocssRequest, MessageModel.TRPT,
                    true);
        }
    }

    private void initTRPT(String tnb, String pid, String rmk, String tst) {
        submittaskprocssRequest = new SubmittaskprocssRequest();
        SubmitTaskProcessRequestVO submittaskprocssrequestVO = new SubmitTaskProcessRequestVO();
        submittaskprocssrequestVO.setIFM("N");
        submittaskprocssrequestVO.setPID(pid);
        submittaskprocssrequestVO.setRMK(rmk);
        submittaskprocssrequestVO.setSDT(S.getNowTime());
        submittaskprocssrequestVO.setTNB(tnb);
        submittaskprocssrequestVO.setTST(tst);
        submittaskprocssRequest
                .setSubmittaskprocssRequestVO(submittaskprocssrequestVO);
    }

    public void updatelist(Object tnb, int action) {
        // 如果更新的TNB不是当前的TNB
        if (!tnb.equals(sTNB)) {
            return;
        }
        if (action == ParameterModel.UI_UPDATE_MONITOR) {
            // 更新监控项信息
            loadMonitorInfo();
            // 如果当前是显示的是监控项列表
            if (!bListService && mSchedule != null) {
                mSchedule.notifyDataSetChanged();
            }
        } else if (action == ParameterModel.UI_UPDATE_SERVICE) {
            // 更新服务标注信息
            loadStandardInfo();
            // 如果当前是显示的服务标注项
            if (bListService && mSchedule != null) {
                mSchedule.notifyDataSetChanged();
            }
        }
    }

    @Override
    public void onClick(View v) {
        // TODO Auto-generated method stub
        if (v == btn_change) {
            function_well();
        }
    }

    @Override
    protected void operateResponseSucess(String serviceId, BaseResponse response) {
        // TODO Auto-generated method stub
        if (serviceId.equals(MessageModel.TRPT)) {
            // 更新监控列表UI
            SubmittaskprocssResponse resp = (SubmittaskprocssResponse) response;
            if ("N".equals(resp.getSubmitTaskProcessResponseVO().getIfsw())) {
                updatelist(resp.getSubmitTaskProcessResponseVO().getTnb(), ParameterModel.UI_UPDATE_MONITOR);
            }
        } else if (serviceId.equals(MessageModel.TMRP)) {
            // 更新服务标注列表UI
            SubmittaskmarkResponse submittaskmarkResponse = (SubmittaskmarkResponse) response;
            updatelist(submittaskmarkResponse.getSubmitTaskMarkResponseVO()
                    .getTnb(), ParameterModel.UI_UPDATE_SERVICE);
            EffectManager.getInstance().ttsPlay(EffectManager.TTS_TYPE_TASK,
                    getString(R.string.service_labelChangeSucceed), false);
        }
    }

    @Override
    protected void updateUI(String tag) {
        // TODO Auto-generated method stub

    }

    @Override
    protected void updateUI(String tag, String tnb) {
        if (tag.equals(MessageModel.REFRESH)) {
            if (tnb.equals(sTNB)) {
                if(MessageModel.TEND.equals(task.getPID()) || MessageModel.TCXX.equals(task.getPID()) || task.getPID().equals(MessageModel.TRJT)){
                    finish();
                }
            }
        }
    }
}
